const app = getApp()

let serverWs = null
let gameId = null
let userId = null
let alpha = 0

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
    games: [],
    connected: true,
    alpha: 1,
  },
  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    wx.onSocketClose((result) => {
      serverWs = null
      this.setData({
        connected: true
      })
    })
    wx.onSocketOpen((result) => {
      console.log('ws connected')
    })

    wx.onAccelerometerChange((res) => {
      // this.wsSend('accelerometer', res)
    })

    wx.onGyroscopeChange((res) => {
      // this.wsSend('gyroscope', res)
    })

    wx.onDeviceMotionChange((res) => {
      this.wsSend('devicemotion', res)
      alpha = res.alpha
      // this.setData({
      //   alpha: parseInt(res.alpha)
      // })
    })
    wx.startAccelerometer({
      interval: 'normal',
      success: (result) => {
        console.log("start accelerometer success")
      },
      fail: () => {},
      complete: () => {}
    });

    wx.startGyroscope({
      interval: 'normal',
      success: (result) => {
        console.log("start gyroscope success")
      },
      fail: () => {},
      complete: () => {}
    })

    wx.startDeviceMotionListening({
      interval: 'ui',
      success: (result) => {
        console.log("start motion listening success")
      },
      fail: () => {},
      complete: () => {}
    });
    setInterval(() => {
      wx.request({
        url: 'https://ps.be4.cn/motion/list',
        success: (res) => {
          this.setData({
            games: res.data
          })
        }
      })
      this.wsConnect()
    }, 2000);
    wx.getUserInfo({
      success: (res) => {
        console.log(res.userInfo)
      },
    })
    this.wsConnect();
    
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    console.log(e)
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  connectGame(e) {
    if(!serverWs) return
    console.log("connect: " + e.currentTarget.dataset)
    gameId = e.currentTarget.dataset['gameid']
    this.wsSend('init', {gameId, alpha})
    this.setData({
      connected: false
    })


  },
  sendAction(e) {
    let action = e.currentTarget.dataset['action']
    this.wsSend('action', { action })
  },
  sendStart(e) {
    let action = e.currentTarget.dataset['action']
    this.wsSend('touchStart', { action })
  },
  sendEnd(e) {
    let action = e.currentTarget.dataset['action']
    this.wsSend('touchEnd', { action })
  },
  
  wsSend(type, data) {
    if(serverWs && gameId) {
      wx.sendSocketMessage({
        data: JSON.stringify({
          gameId,
          type,
          data
        })
      })
    }
  },

  wsConnect() {
    if(serverWs)
      return;
    serverWs = wx.connectSocket({
      url: 'wss://ps.be4.cn/motion/ws/?userId=1',
      header: {
        'content-type': 'application/json'
      },
      fail: (res) => {
        serverWs = null
      }
    })
  },
})
